package com.uft.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uft.model.dao.DPProfileDAO;
import com.uft.model.entity.DPProfile;
import com.uft.model.entity.DPRuntime;
import com.uft.model.entity.Profile;

@Controller
public class DatapowerController {
	
	@Autowired
	public DPProfileDAO dpProfileDao;
	private  static Logger  logger = Logger.getLogger(DatapowerController.class);
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getDPProfileList", method = RequestMethod.POST)
	@ResponseBody
	public String getDPProfileList(HttpServletRequest request) {
		String result="";
		List<DPProfile> DPProfileList= new ArrayList<DPProfile>();
		try{
			DPProfileList=dpProfileDao.getDPProfileList();
			
			
			  
			ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(DPProfileList);
			result="{\"Result\":\"OK\",\"Records\":"+listData+"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
		}
		logger.debug("result "+result);
		return result;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/addDPProfile", method = RequestMethod.POST)
	@ResponseBody
	public String addDPProfile(DPProfile dpProfile,HttpServletRequest request){
		String result="";
		try{
			//Profile profileBean= getBeanFromRequest(request);
			logger.debug("DP ProfileName: Add new  "+dpProfile.getDpName());
			dpProfileDao.addDPProfile(dpProfile);
			
			ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(dpProfile);
			
			result="{\"Result\":\"OK\",\"Record\":"+listData+"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/updateDPProfile", method = RequestMethod.POST)
	@ResponseBody
	public String updateDPProfile(DPProfile dpProfile,HttpServletRequest request){
		String result="";
		try{
			//Profile profileBean= getBeanFromRequest(request);
			logger.debug("DP ProfileName: update   "+dpProfile.getDpName());
			dpProfileDao.updateDPProfile(dpProfile);
			
		    ObjectMapper mapper = new ObjectMapper();
			String listData=mapper.writeValueAsString(dpProfile);
		
			result="{\"Result\":\"OK\",\"Record\":"+listData+"}";
		}catch(Exception ex){
			result="{\"Result\":\"ERROR\",\"Message\":\""+ex.getMessage()+"\"}";
			ex.printStackTrace();
			
		}
		logger.debug(result);
		return result;
	}
	@PreAuthorize("hasRole('ROLE_ADMIN')")
	@RequestMapping(value="/getDatapowerView", method = RequestMethod.GET)
	public ModelAndView getDatapowerView(HttpServletRequest request,  
            HttpServletResponse response){
		ModelAndView model = new ModelAndView("datapower");
		logger.debug("get datapower Vieiw");
		return model;
	}
	@RequestMapping(value="/getDpRunTimeDataByStartEnd", method = RequestMethod.POST)
	@ResponseBody
	public String getDpRunTimeDataByStartEnd(@RequestParam(value="dpName", required=true) String dpName,
								   @RequestParam(value="startTime",required=true) String startTime,
								   @RequestParam(value="endTime",required=true) String endTime,
			HttpServletRequest request){
		String result="";
		logger.debug("Dp Name : "+dpName);
		logger.debug("startTime : "+startTime);
		logger.debug("endTime : "+endTime);
		
		DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		Date fromDate;
		Date toDate;
		try {
			fromDate = (Date)formatter.parse(startTime);
			logger.debug("endTime Date : "+fromDate);
			Calendar fromCal = Calendar.getInstance();
			fromCal.setTime(fromDate);
			
			toDate = (Date)formatter.parse(endTime);
			logger.debug("endTime Date : "+toDate);
			Calendar toCal = Calendar.getInstance();
			toCal.setTime(toDate);
			
			result=getDpRuntime(dpName,fromCal.getTime(),toCal.getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	public String getDpRuntime(String dpName, Date startTime, Date endTime){
		String result="";
		List<DPRuntime> dpLst=dpProfileDao.getDPRuntimeByStartEnd(dpName, startTime, endTime);
		List<HashMap<String,Object>> listR=new ArrayList<HashMap<String,Object>>();
		
		ObjectMapper mapper = new ObjectMapper();
		if(dpLst.size() > 0){
			for(int i=0; i<dpLst.size();i++){
				HashMap<String,Object> props = mapper.convertValue(dpLst.get(i), HashMap.class);
				props.putAll(calDpRuntime(dpLst.get(i)));
				listR.add(props);
			}
		}
		String listData;
		try {
			listData = mapper.writeValueAsString(listR);
			logger.debug("List dat: "+listData);
			result="{\"Result\":\"OK\",\"Records\":"+listData+"}";
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			result="{\"Result\":\"ERROR\",\"Message\":\""+e.getMessage()+"\"}";
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			result="{\"Result\":\"ERROR\",\"Message\":\""+e.getMessage()+"\"}";
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			result="{\"Result\":\"ERROR\",\"Message\":\""+e.getMessage()+"\"}";
			e.printStackTrace();
		}
		
		return result;
	}
	
	public HashMap<String,Object> calDpRuntime(DPRuntime dpRuntime){
		HashMap<String,Object> result= new HashMap<String,Object>();
		int memoryUsage=Integer.parseInt(dpRuntime.getUsedMemory())/Integer.parseInt(dpRuntime.getTotalMemory())*100;
		result.put("memoryUsage", memoryUsage);
		return result;
	}
	
}
